<template>
    <div>
        <el-upload
                :action="action"
                :multiple="limit>1"
                :limit="limit"
                list-type="picture-card"
                :http-request="uploadImg"
                :on-success="uploadImgSuccess"
                :before-upload="beforeUploadHandler"
                :on-remove="uploadImgRemove"
                :file-list="imgList">
            <i class="el-icon-plus"/>
        </el-upload>
    </div>
</template>

<script>
    import * as upload from '@/utils/upload'

    export default {
        name: "index",
        props: {
            imgList: {
                type: Array,
                default() {
                    return []
                }
            },
            limit: {
                type: Number,
                default() {
                    return 1
                }
            }
        },
        data() {
            return {
                count: 0,
                action: '',
            }
        },
        methods: {
            uploadImg(option) {
                upload.upload(option)
            },
            beforeUploadHandler(file) {
                let fileName = file.name.split('.')
                let suffix = fileName[fileName.length - 1]
                const imgList = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
                let isImg = imgList.some(function (item) {
                    return item === suffix
                })
                const isLt2M = file.size / 1024 / 1024 < 2

                if (!isImg) {
                    this.$message.error('上传图片只能是 JPG|GIF/PNG/BMP 格式!')
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!')
                }
                return isImg && isLt2M
            },
            uploadImgSuccess(value) {
                this.count++
                this.$emit("on-uploadImgSuccess", value)
            },
            uploadImgRemove(value) {
                this.count--
                this.$emit("on-uploadImgRemove", value)
            },
        }
    }
</script>

<style scoped>

</style>
